package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.extend.WorkBackVisitTemplateModuleExtend;
import com.zb.mapper.ZjWorkBackVisitTemplateMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjWorkBackVisitTemplateFieldContentService;
import com.zb.service.ZjWorkBackVisitTemplateFieldService;
import com.zb.service.ZjWorkBackVisitTemplateModuleService;
import com.zb.service.ZjWorkBackVisitTemplateService;
import com.zb.vo.OrderModuleFieldListVo;
import com.zb.vo.TemplateModuleVo;
import com.zb.vo.WorkStatementTemplateListVo;
import com.zb.vo.WorkStatementTemplateVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单回访模板表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-10-08
 */
@Service
public class ZjWorkBackVisitTemplateServiceImpl extends ServiceImpl<ZjWorkBackVisitTemplateMapper, ZjWorkBackVisitTemplate> implements ZjWorkBackVisitTemplateService {
    @Resource
    private ZjWorkBackVisitTemplateMapper workBackVisitTemplateMapper;
    @Resource
    private ZjWorkBackVisitTemplateModuleService workBackVisitTemplateModuleService;
    @Resource
    private ZjWorkBackVisitTemplateFieldService workBackVisitTemplateFieldService;
    @Resource
    private ZjWorkBackVisitTemplateFieldContentService workBackVisitTemplateFieldContentService;

    // 新增或修改回访模板
    @Override
    @Transactional
    public void save(AccounLoginInfo loginInfo, WorkStatementTemplateVo templateVo) {
        Assert.isTrue(null == workBackVisitTemplateMapper.existByName(loginInfo.getCustAccId(), templateVo.getId(), templateVo.getName()), "回访模板[" + templateVo.getName() + "]已重复！");
        ZjWorkBackVisitTemplate template = new ZjWorkBackVisitTemplate();
        BeanUtil.copyProperties(templateVo, template);
        template.setDisabled(templateVo.getStatus());
        template.setUpdateEmpId(loginInfo.getId());
        template.setUpdateEmp(loginInfo.getName());
        if (null != template.getId()) {
            this.updateById(template);
        } else {
            template.setId(IdWorker.getId());
            template.setCustAccId(loginInfo.getCustAccId());
            template.setCreateEmpId(loginInfo.getId());
            template.setCreateEmp(loginInfo.getName());
            this.save(template);
        }
        workBackVisitTemplateModuleService.save(loginInfo.getCustAccId(), template.getId(), templateVo.getTemplateModuleIds(), templateVo.getDelTemplateModuleIds());
        workBackVisitTemplateFieldService.save(loginInfo.getCustAccId(), template.getId(), templateVo.getTemplateField());
    }

    // 获取回访模板列表
    @Override
    public Map<String, Object> getList(Long custAccId, SelectVo selectVo) {
        PageUtil.setPageLimit(selectVo);
        QueryWrapper<ZjWorkBackVisitTemplate> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_update");
        wrapper.eq("cust_acc_id", custAccId);
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        Page<ZjWorkBackVisitTemplate> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        List<Long> ids = page.getRecords().stream().map(ZjWorkBackVisitTemplate::getId).toList();
        List<WorkBackVisitTemplateModuleExtend> moduleExtends = workBackVisitTemplateModuleService.getByWorkBackVisitTemplateIds(ids);

        List<WorkStatementTemplateListVo> voList = page.getRecords().stream().map(tem -> {
            WorkStatementTemplateListVo vo = new WorkStatementTemplateListVo();
            BeanUtil.copyProperties(tem, vo);
            vo.setStatus(tem.getDisabled());
            vo.setCreateTime(tem.getGmtCreate());
            vo.setUpdateTime(tem.getGmtUpdate());
            vo.setModuleName(moduleExtends.stream().filter(f -> Objects.equals(f.getWorkBackVisitTemplateId(), tem.getId())).map(WorkBackVisitTemplateModuleExtend::getModuleName).collect(Collectors.joining("、")));
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 根据回访ID获取回访详情
    @Override
    public WorkStatementTemplateVo getDetail(Long id) {
        ZjWorkBackVisitTemplate template = this.getById(id);
        Assert.isTrue(null != template, "回访模板ID参数[" + id + "]的数据不存在！");

        WorkStatementTemplateVo vo = new WorkStatementTemplateVo();
        BeanUtil.copyProperties(template, vo);
        vo.setStatus(template.getDisabled());
        vo.setTemplateModuleIds(workBackVisitTemplateModuleService.getByWorkBackVisitTemplateId(id).stream().map(mo -> {
            TemplateModuleVo mv = new TemplateModuleVo();
            BeanUtil.copyProperties(mo, mv);
            return mv;
        }).toList());
        vo.setTemplateField(workBackVisitTemplateFieldService.getByWorkBackVisitTemplateId(id));
        return vo;
    }

    // 批量启用或禁用回访模板
    @Override
    public void updateDisableBatchById(AccounLoginInfo loginInfo, List<Long> ids, boolean status) {
        workBackVisitTemplateMapper.updateDisableBatchById(loginInfo, ids, status);
    }

    // 批量删除回访模板
    @Override
    @Transactional
    public void deleteBatchById(List<Long> ids) {
        List<Long> fieldIds = workBackVisitTemplateFieldService.getByWorkBackVisitTemplateIds(ids).stream().map(ZjWorkBackVisitTemplateField::getId).toList();
        List<ZjWorkBackVisitTemplateField> relationFields = workBackVisitTemplateFieldService.getRelationByIds(fieldIds);
        if (CollectionUtils.isNotEmpty(relationFields)) {
            List<Long> templateIds = relationFields.stream().map(ZjWorkBackVisitTemplateField::getWorkBackVisitTemplateId).distinct().toList();
            QueryWrapper<ZjWorkBackVisitTemplate> wrapper = new QueryWrapper<>();
            wrapper.select("name");
            wrapper.in("id", templateIds);
            String templateName = this.list(wrapper).stream().map(ZjWorkBackVisitTemplate::getName).collect(Collectors.joining("、"));
            String fieldName = relationFields.stream().map(ZjWorkBackVisitTemplateField::getName).collect(Collectors.joining("、"));
            Assert.isTrue(false, "回访模板[" + templateName + "]下的自定义字段[" + fieldName + "]已被使用中，不可删除");
        }
        workBackVisitTemplateFieldService.deleteBatchByWorkBackVisitTemplateIds(ids);
        workBackVisitTemplateModuleService.deleteBatchByWorkBackVisitTemplateIds(ids);
        this.removeByIds(ids);
    }

    // 获取工单模块回访自定义字段列表
    @Override
    public Map<String, Object> getModuleField(Long moduleId, SelectVo selectVo) {
        PageUtil.setPageLimit(selectVo);
        List<ZjWorkBackVisitTemplateModule> templateModules = workBackVisitTemplateModuleService.getByModuleId(moduleId);
        if (CollectionUtils.isEmpty(templateModules)) {
            return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), 0L, new ArrayList<>());
        }
        List<Long> templateIds = templateModules.stream().map(ZjWorkBackVisitTemplateModule::getWorkBackVisitTemplateId).distinct().toList();

        QueryWrapper<ZjWorkBackVisitTemplate> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        wrapper.in("id", templateIds);
        List<ZjWorkBackVisitTemplate> templateList = this.list(wrapper);

        QueryWrapper<ZjWorkBackVisitTemplateField> fieldQueryWrapper = new QueryWrapper<>();
        fieldQueryWrapper.in("work_back_visit_template_id", templateIds);
        if (StringUtils.isNotBlank(selectVo.getName())) {
            fieldQueryWrapper.like("name", selectVo.getName());
        }
        Page<ZjWorkBackVisitTemplateField> page = workBackVisitTemplateFieldService.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), fieldQueryWrapper);

        List<Long> fieldIds = page.getRecords().stream().map(ZjWorkBackVisitTemplateField::getId).toList();
        List<ZjWorkBackVisitTemplateFieldContent> contentList = workBackVisitTemplateFieldContentService.getByWorkBackVisitTemplateFieldIds(fieldIds);

        List<OrderModuleFieldListVo> voList = page.getRecords().stream().map(tem -> {
            OrderModuleFieldListVo vo = new OrderModuleFieldListVo();
            BeanUtil.copyProperties(tem, vo);
            vo.setUpdateTime(tem.getGmtUpdate());
            vo.setTemplate(templateList.stream().filter(f -> Objects.equals(f.getId(), tem.getWorkBackVisitTemplateId())).map(ZjWorkBackVisitTemplate::getName).findFirst().orElse(""));
            vo.setContent(contentList.stream().filter(f -> Objects.equals(f.getWorkBackVisitTemplateFieldId(), tem.getId())).map(ZjWorkBackVisitTemplateFieldContent::getVal).collect(Collectors.joining("、")));
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 根据回访模板ID获取回访模板信息
    @Override
    public List<ZjWorkBackVisitTemplate> getByIds(List<Long> ids) {
        if (null == ids || ids.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjWorkBackVisitTemplate> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        wrapper.in("id", ids);
        return this.list(wrapper);
    }
}
